<template>
  <div class="recipe-list-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="食谱大全"
      left-arrow
      fixed
      @click-left="$router.back()"
    />
    <div class="nav-placeholder"></div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-area">
      <!-- 搜索框 -->
      <van-search
        v-model="searchText"
        placeholder="搜索食谱名称、食材"
        shape="round"
        clearable
        @search="onSearch"
      />

      <!-- 筛选标签栏 -->
      <div class="filter-tabs">
        <van-tabs
          v-model:active="activeCategory"
          sticky
          swipeable
          @change="handleCategoryChange"
        >
          <van-tab
            v-for="category in categories"
            :key="category.id"
            :title="category.name"
          />
        </van-tabs>
      </div>

      <!-- 高级筛选 -->
      <div class="advanced-filter">
        <van-dropdown-menu>
          <van-dropdown-item
            v-model="sortValue"
            :options="sortOptions"
            @change="handleSortChange"
          />
          <van-dropdown-item
            v-model="difficultyValue"
            :options="difficultyOptions"
            @change="handleFilterChange"
          />
          <van-dropdown-item
            v-model="cookTimeValue"
            :options="cookTimeOptions"
            @change="handleFilterChange"
          />
        </van-dropdown-menu>
      </div>
    </div>

    <!-- 食谱列表 -->
    <div class="recipe-content">
      <template v-if="loading">
        <div class="loading-container">
          <van-loading type="spinner" size="24px">加载中...</van-loading>
        </div>
      </template>

      <template v-else-if="recipeList.length === 0">
        <van-empty description="没有找到符合条件的食谱" />
      </template>

      <template v-else>
        <div class="recipe-grid">
          <div
            v-for="recipe in recipeList"
            :key="recipe.id"
            class="recipe-card"
            @click="navigateToDetail(recipe.id)"
          >
            <div class="recipe-image">
              <van-image
                :src="recipe.image"
                fit="cover"
                radius="4"
                width="100%"
                height="120"
              />
              <div
                class="recipe-difficulty"
                :class="`difficulty-${recipe.difficulty}`"
              >
                {{ getDifficultyText(recipe.difficulty) }}
              </div>
            </div>
            <div class="recipe-info">
              <div class="recipe-name">{{ recipe.name }}</div>
              <div class="recipe-desc">{{ recipe.description }}</div>
              <div class="recipe-meta">
                <div class="cook-time">
                  <van-icon name="underway-o" size="12" />
                  <span>{{ recipe.cookTime }}分钟</span>
                </div>
                <div class="rating">
                  <van-rate
                    v-model="recipe.rating"
                    size="12"
                    readonly
                    allow-half
                  />
                  <span>({{ recipe.ratingCount }})</span>
                </div>
              </div>
              <div class="recipe-tags">
                <van-tag
                  plain
                  type="primary"
                  size="mini"
                  v-for="tag in recipe.tags"
                  :key="tag"
                >
                  {{ tag }}
                </van-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <van-pagination
            v-model="currentPage"
            :total-items="totalItems"
            :items-per-page="pageSize"
            mode="simple"
            @change="handlePageChange"
          />
        </div>
      </template>
    </div>

    <!-- 回到顶部 -->
    <van-back-top right="16" bottom="80" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { showToast } from "vant";

const router = useRouter();

// 搜索和筛选状态
const searchText = ref("");
const activeCategory = ref(0);
const sortValue = ref("newest");
const difficultyValue = ref("all");
const cookTimeValue = ref("all");

// 分页状态
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);

// 加载状态
const loading = ref(true);

// 菜谱分类
const categories = ref([
  { id: 0, name: "全部" },
  { id: 1, name: "家常菜" },
  { id: 2, name: "快手菜" },
  { id: 3, name: "下饭菜" },
  { id: 4, name: "早餐" },
  { id: 5, name: "午餐" },
  { id: 6, name: "晚餐" },
  { id: 7, name: "小吃" },
  { id: 8, name: "素食" },
  { id: 9, name: "沙拉" },
  { id: 10, name: "汤羹" },
  { id: 11, name: "主食" },
  { id: 12, name: "甜品" },
]);

// 排序选项
const sortOptions = [
  { text: "最新", value: "newest" },
  { text: "最热", value: "popular" },
  { text: "评分最高", value: "rating" },
  { text: "烹饪时间最短", value: "cookTime" },
];

// 难度选项
const difficultyOptions = [
  { text: "全部难度", value: "all" },
  { text: "简单", value: 1 },
  { text: "中等", value: 2 },
  { text: "困难", value: 3 },
];

// 烹饪时间选项
const cookTimeOptions = [
  { text: "全部时间", value: "all" },
  { text: "15分钟以内", value: 15 },
  { text: "30分钟以内", value: 30 },
  { text: "60分钟以内", value: 60 },
  { text: "60分钟以上", value: 61 },
];

// 食谱数据
const recipeList = ref([]);

// 获取食谱列表（模拟API调用）
const fetchRecipes = async () => {
  loading.value = true;
  try {
    // 这里应该是真实的API调用
    console.log("获取食谱列表", {
      page: currentPage.value,
      pageSize: pageSize.value,
      category:
        activeCategory.value === 0
          ? null
          : categories.value[activeCategory.value].id,
      keyword: searchText.value,
      sort: sortValue.value,
      difficulty: difficultyValue.value,
      cookTime: cookTimeValue.value,
    });

    // 模拟API响应
    await new Promise((resolve) => setTimeout(resolve, 800));

    // 模拟数据
    const mockRecipes = generateMockRecipes();
    recipeList.value = mockRecipes;
    totalItems.value = 56; // 模拟总数
  } catch (error) {
    console.error("获取食谱列表失败", error);
    showToast("获取食谱列表失败");
  } finally {
    loading.value = false;
  }
};

// 生成模拟数据
const generateMockRecipes = () => {
  return Array.from({ length: 10 }, (_, i) => ({
    id: i + 1 + (currentPage.value - 1) * 10,
    name: `美味食谱 ${i + 1 + (currentPage.value - 1) * 10}`,
    description: "这是一道健康美味的食谱，适合家庭烹饪。",
    image: `https://img01.yzcdn.cn/vant/cat.jpeg`,
    difficulty: Math.floor(Math.random() * 3) + 1,
    cookTime: [15, 25, 40, 60, 90][Math.floor(Math.random() * 5)],
    rating: (Math.random() * 2 + 3).toFixed(1), // 3.0-5.0
    ratingCount: Math.floor(Math.random() * 200) + 10,
    tags: ["健康", "家常", "简单"].slice(0, Math.floor(Math.random() * 3) + 1),
  }));
};

// 获取难度文本
const getDifficultyText = (level) => {
  const texts = ["", "简单", "中等", "困难"];
  return texts[level] || "";
};

// 处理搜索
const onSearch = () => {
  currentPage.value = 1;
  fetchRecipes();
};

// 处理分类切换
const handleCategoryChange = () => {
  currentPage.value = 1;
  fetchRecipes();
};

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1;
  fetchRecipes();
};

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1;
  fetchRecipes();
};

// 处理分页变化
const handlePageChange = () => {
  fetchRecipes();
  // 滚动到顶部
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};

// 导航到食谱详情
const navigateToDetail = (id) => {
  router.push(`/recipe/${id}`);
};

// 初始化
onMounted(() => {
  fetchRecipes();
});
</script>

<style scoped>
.recipe-list-container {
  padding-bottom: 50px;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.nav-placeholder {
  height: 46px;
}

.search-filter-area {
  background-color: #fff;
  border-bottom: 1px solid #f5f5f5;
}

.filter-tabs {
  margin-bottom: 8px;
}

.advanced-filter {
  margin-bottom: 8px;
}

.recipe-content {
  padding: 10px 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 60px 0;
}

.recipe-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.recipe-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: transform 0.2s;
}

.recipe-card:active {
  transform: scale(0.98);
}

.recipe-image {
  position: relative;
}

.recipe-difficulty {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 2px 6px;
  font-size: 12px;
  color: #fff;
  border-radius: 10px;
}

.difficulty-1 {
  background-color: #4caf50;
}

.difficulty-2 {
  background-color: #ff9800;
}

.difficulty-3 {
  background-color: #f44336;
}

.recipe-info {
  padding: 10px;
}

.recipe-name {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.recipe-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 36px;
}

.recipe-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 12px;
  color: #999;
}

.cook-time {
  display: flex;
  align-items: center;
  gap: 4px;
}

.rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.recipe-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
